package ru.evga.gwt.lib.common.client.ui.editor;

import java.util.List;

import com.google.gwt.editor.client.Editor;
import com.google.gwt.editor.client.EditorError;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.google.gwt.user.client.ui.IsWidget;


public class EditManager<T, E extends Editor<? super T>, W extends IsWidget>
{
    private EditCallback<T> callback;
    private T data;
    private E editor;
    private W editorPanel;
    private SimpleBeanEditorDriver<T, E> driver;

    public interface EditCallback<T>
    {
        /**
         * 
         * @param editedData 
         */
        void onSave(T editedData);

        /**
         * @param editedData
         */
        void onCancel(T editedData);

        /**
         * On error happens
         * @param errors
         */
        void onError(List<EditorError> errors);
    };


    public void init(T data, E editor, W panel, EditCallback<T> callback, SimpleBeanEditorDriver<T, E> driver)
    {
        this.callback = callback;
        this.data = data;
        this.editor = editor;
        this.editorPanel = panel;
        this.driver = driver;
    }

    public void save()
    {
        driver.flush();
        if (driver.hasErrors())
        {
            callback.onError(driver.getErrors());
        }
        
        callback.onSave(data);
    }

    /**
     * Creates content
     */
    public IsWidget createContent()
    {
        driver.initialize(editor);
        driver.edit(data);
        return editorPanel.asWidget();
    }

    public void cancel()
    {
        callback.onCancel(data);
    }
    
    public T getEditedData()
    {
        return this.data;
    }
}
